<?php

namespace common\helpers;

use Yii;
use yii\helpers\BaseIpHelper;
use yii\helpers\Json;

/**
 * Class IpHelper provides a set of IP-related static methods.
 *
 * Methods expect correct IP addresses.
 * To validate IP addresses use [[\yii\validators\IpValidator|IpValidator]].
 *
 * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
 * @since 2.0.14
 */
class IpHelper extends BaseIpHelper {

    /**
     * IP地址转换成长整型格式
     * @param string $ip
     * @param boolean $unsigned
     * @return integer
     */
    public static function ip2long($ip, $unsigned = true) {
        $long = ip2long($ip);
        if ($unsigned == true) {
            return sprintf('%u', $long);
        }
        return $long;
    }

    /**
     * 长整型数字格式成IP地址
     * @param integer $long
     * @return string IP
     */
    public static function long2ip($long, $simple = true) {
        $ip = long2ip($long);
        if ($simple === true) {
            return $ip;
        }
        $url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
        $remote = file_get_contents($url);
        $data = Json::decode($remote);
        if (empty($data) || !isset($data['data'])) {
            return $ip;
        }
        return $data['data'];
    }

    /**
     * 长整型数字格式成IP地址
     * @param boolean $long
     * @return integer user IP
     */
    public static function ip($long = true) {
        $ip = Yii::$app->request->userIP;
        if ($long) {
            return static::ip2long($ip);
        }
        return $ip;
    }

    public static function getServerIp() {
        $ipPython = Yii::getAlias('@common/data/python/ip.py');
        $data = [];
        exec("python3 $ipPython", $data);
        return array_pop($data);
    }

    /**
     * 获取客户端的真实IP
     * @return string 真实IP地址
     */
    public static function getRealIp() {

        if (getenv('HTTP_X_REAL_IP')) {
            return getenv('HTTP_X_REAL_IP');
        }
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $remote_addr = getenv("HTTP_X_FORWARDED_FOR");
            $tmp_ip = explode(",", $remote_addr);
            return $tmp_ip[0];
        }
        if (getenv('HTTP_CLIENT_IP')) {
            return getenv('HTTP_CLIENT_IP');
        }
        if (getenv('REMOTE_ADDR')) {
            return getenv('REMOTE_ADDR');
        }
        if (isset($_SERVER['REMOTE_ADDR'])) {
            return $_SERVER['REMOTE_ADDR'];
        }
        return '';
    }

}
